package com.getpebble.android.jsbridge;

import android.text.TextUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.getpebble.android.common.core.trace.Trace;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public abstract class JsBridgeWebClient extends WebViewClient {
    public static final String TAG = JsBridgeWebClient.class.getSimpleName();

    protected abstract void handleJSBridgeMethods(String str, JSONObject jSONObject);

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!url.startsWith("pebble-method-call-js-frame://")) {
            return super.shouldOverrideUrlLoading(view, url);
        }
        try {
            onQueryParamsReceived(JsBridgeUtil.getQueryParams(url));
        } catch (Exception e) {
            Trace.error(TAG, "Failed to handle queryParams.", e);
        }
        return false;
    }

    private void onQueryParamsReceived(Map<String, String> params) {
        JSONException e;
        String methodArgsJson = (String) params.get("args");
        if (methodArgsJson != null) {
            String methodName = null;
            JSONObject methodArgs = null;
            try {
                JSONObject methodArgs2 = new JSONObject(methodArgsJson);
                try {
                    methodName = methodArgs2.optString("methodName");
                    methodArgs = methodArgs2;
                } catch (JSONException e2) {
                    e = e2;
                    methodArgs = methodArgs2;
                    Trace.error(TAG, "JSONException in handleQueryParams for methodArgsJson:" + methodArgsJson, e);
                    if (TextUtils.isEmpty(methodName)) {
                        handleJSBridgeMethods(methodName, methodArgs);
                    } else {
                        Trace.warning(TAG, "Got empty methodName");
                    }
                }
            } catch (JSONException e3) {
                e = e3;
                Trace.error(TAG, "JSONException in handleQueryParams for methodArgsJson:" + methodArgsJson, e);
                if (TextUtils.isEmpty(methodName)) {
                    handleJSBridgeMethods(methodName, methodArgs);
                } else {
                    Trace.warning(TAG, "Got empty methodName");
                }
            }
            if (TextUtils.isEmpty(methodName)) {
                handleJSBridgeMethods(methodName, methodArgs);
            } else {
                Trace.warning(TAG, "Got empty methodName");
            }
        }
    }
}
